package work;
import java.net.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FinalServer implements Runnable {
    DatagramSocket socket;
    byte[] buffer = new byte[8192];
    InetAddress clientAddress;
    int clientPort;

    // 日志文件
    File sendLogFile = new File("Server_out_log.txt");
    File receiveLogFile = new File("Server_in_log.txt");

    FinalServer() throws SocketException {
        socket = new DatagramSocket(5678); // 绑定到 5678 端口
        new Thread(this).start(); // 启动接收线程
        System.out.println("服务器已启动，等待消息...");
    }

    // 接收客户端发送的消息
    @Override
    public void run() {
        while (true) {
            try {
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                socket.receive(packet); // 接收消息

                String receivedMessage = new String(packet.getData(), 0, packet.getLength());
                clientAddress = packet.getAddress(); // 获取客户端的地址
                clientPort = packet.getPort(); // 获取客户端的端口

                System.out.println("【提示】收到数据来自：" + clientAddress + "，端口：" + clientPort);
                System.out.println("【提示】收到的消息是：" + receivedMessage);

                // 写入接收日志
                logMessage(receiveLogFile, "接收", clientAddress, receivedMessage);

                // 如果收到 "exit"，关闭接收线程
                if (receivedMessage.trim().equalsIgnoreCase("exit")) {
                    System.out.println("【提示】客户端请求退出聊天，接收线程关闭...");
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close(); // 关闭服务器端口
        System.out.println("【提示】服务器接收线程已关闭。");
    }

    // 发送数据到客户端
    public void sendMessage(String message) {
        if (!message.isEmpty() && clientAddress != null && clientPort != 0) {
            try {
                DatagramPacket packet = new DatagramPacket(
                        message.getBytes(),
                        message.length(),
                        clientAddress,
                        clientPort);
                socket.send(packet);

                System.out.println("【提示】消息发送成功：" + message);
                // 写入发送日志
                logMessage(sendLogFile, "发送", clientAddress, message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("【警告】未指定客户端地址和端口，无法发送消息！");
        }
    }

    // 写入日志的方法
    private void logMessage(File logFile, String action, InetAddress address, String message) {
        try (PrintWriter writer = new PrintWriter(new FileWriter(logFile, true))) {
            String timestamp = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").format(new Date());
            writer.printf("%s: %s 时间: %s 内容: %s%n", action, address, timestamp, message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        FinalServer server = new FinalServer();
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

        while (true) {
            System.out.print("输入要发送的消息（输入 'exit' 退出）：");
            String message = console.readLine();

            // 如果输入 "exit"，退出程序
            if (message.trim().equalsIgnoreCase("exit")) {
                System.out.println("【提示】服务器退出发送循环...");
                server.sendMessage("服务器已断开连接");
                break;
            }

            server.sendMessage(message);
        }
    }
}